{% extends "base.html" %}
{% load widget_tweaks %}

{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h4 class="mb-0">{% if form.instance.pk %}编辑{% else %}创建{% endif %}订阅</h4>
        </div>
        <div class="card-body">
            <form method="post" id="subscription-form" novalidate>
                {% csrf_token %}
                
                {% if form.non_field_errors %}
                <div class="alert alert-danger">
                    {% for error in form.non_field_errors %}
                        {{ error }}
                    {% endfor %}
                </div>
                {% endif %}
                
                {# 数据源选择 #}
                <div class="mb-3">
                    <label for="{{ form.data_source.id_for_label }}" class="form-label required">数据源</label>
                    {{ form.data_source|add_class:"form-control" }}
                    {% if form.data_source.help_text %}
                        <div class="form-text">{{ form.data_source.help_text }}</div>
                    {% endif %}
                </div>

                {# MQTT主题 - 仅MQTT数据源显示 #}
                <div class="mb-3" id="mqtt-topic-group" style="display:none;">
                    <label for="mqtt-topic" class="form-label">MQTT主题</label>
                    <input type="text" class="form-control" id="mqtt-topic" name="topic" 
                           value="{{ form.instance.topic|default:'' }}">
                    <div class="form-text">MQTT订阅的主题，例如：device/data</div>
                </div>

                {# 数据点列表 #}
                <div id="datapoints-container">
                    <h5 class="mb-3">数据点配置</h5>
                    {% if form.instance.pk %}
                        {# 编辑模式 #}
                        <div class="datapoint-item mb-3">
                            <div class="row mb-2">
                                <div class="col">
                                    <label class="form-label required">节点ID/数据点ID</label>
                                    <input type="text" class="form-control node-id" name="node_ids[]" 
                                           value="{{ form.instance.node_id }}" required>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3">
                                    <label class="form-label required">报警条件</label>
                                    <select class="form-control condition" name="conditions[]">
                                        {% for value, label in condition_choices %}
                                        <option value="{{ value }}" 
                                                {% if form.instance.condition == value %}selected{% endif %}>
                                            {{ label }}
                                        </option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label required">阈值</label>
                                    <input type="number" class="form-control threshold" name="thresholds[]" 
                                           value="{{ form.instance.threshold_value }}" step="any" required>
                                </div>
                                <div class="col-md-2 threshold-max-group" 
                                     style="display:{% if form.instance.condition == 'range' %}block{% else %}none{% endif %};">
                                    <label class="form-label">最大阈值</label>
                                    <input type="number" 
                                           class="form-control threshold-max" 
                                           name="threshold_maxs[]" 
                                           value="{% if form.instance.threshold_max != None %}{{ form.instance.threshold_max }}{% endif %}"
                                           step="any">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">单位</label>
                                    <input type="text" class="form-control unit" name="units[]" 
                                           value="{{ form.instance.unit }}">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">报警消息</label>
                                    <input type="text" class="form-control alert-message" name="alert_messages[]" 
                                           value="{{ form.instance.alert_message }}" 
                                           placeholder="数值超出阈值">
                                </div>
                            </div>
                        </div>
                    {% else %}
                        {# 创建模式 #}
                        <div class="datapoint-item mb-3">
                            <div class="row mb-2">
                                <div class="col">
                                    <label class="form-label required">节点ID/数据点ID</label>
                                    <input type="text" class="form-control node-id" name="node_ids[]" required>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3">
                                    <label class="form-label required">报警条件</label>
                                    <select class="form-control condition" name="conditions[]">
                                        {% for value, label in condition_choices %}
                                        <option value="{{ value }}">{{ label }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label required">阈值</label>
                                    <input type="number" class="form-control threshold" name="thresholds[]" 
                                           step="any" required>
                                </div>
                                <div class="col-md-2 threshold-max-group" style="display:none;">
                                    <label class="form-label">最大阈值</label>
                                    <input type="number" class="form-control threshold-max" name="threshold_maxs[]" 
                                           step="any">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">单位</label>
                                    <input type="text" class="form-control unit" name="units[]">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">报警消息</label>
                                    <input type="text" class="form-control alert-message" name="alert_messages[]" 
                                           placeholder="数值超出阈值">
                                </div>
                            </div>
                        </div>
                    {% endif %}
                </div>

                {# 添加数据点按钮 - 仅MQTT数据源显示 #}
                <div class="mb-3" id="add-datapoint-group" style="display:none;">
                    <button type="button" class="btn btn-outline-primary" onclick="addDatapoint()">
                        <i class="bi bi-plus"></i> 添加数据点
                    </button>
                </div>

                <div class="d-flex justify-content-between">
                    <a href="{% url 'subscription_list' %}" class="btn btn-secondary">返回</a>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

{% block extra_css %}
<style>
.required:after {
    content: " *";
    color: red;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
// 根据数据源类型显示/隐藏相关字段
function toggleSourceTypeFields() {
    const sourceSelect = document.getElementById('{{ form.data_source.id_for_label }}');
    const selectedOption = sourceSelect.options[sourceSelect.selectedIndex];
    const isMQTT = selectedOption.text.includes('MQTT');
    
    document.getElementById('mqtt-topic-group').style.display = isMQTT ? 'block' : 'none';
    document.getElementById('add-datapoint-group').style.display = isMQTT ? 'block' : 'none';
}

// 添加新的数据点配置
function addDatapoint() {
    const template = document.querySelector('.datapoint-item').cloneNode(true);
    // 清空所有输入值
    template.querySelectorAll('input').forEach(input => input.value = '');
    // 重置选择框
    template.querySelectorAll('select').forEach(select => select.selectedIndex = 0);
    // 隐藏最大阈值字段
    template.querySelector('.threshold-max-group').style.display = 'none';
    // 添加删除按钮
    const deleteBtn = document.createElement('button');
    deleteBtn.type = 'button';
    deleteBtn.className = 'btn btn-danger btn-sm mt-2';
    deleteBtn.innerHTML = '<i class="bi bi-trash"></i> 删除';
    deleteBtn.onclick = function() {
        this.closest('.datapoint-item').remove();
    };
    template.appendChild(deleteBtn);
    // 添加到容器
    document.getElementById('datapoints-container').appendChild(template);
}

// 切换阈值范围字段
function toggleThresholdFields(select) {
    const maxGroup = select.closest('.datapoint-item').querySelector('.threshold-max-group');
    maxGroup.style.display = select.value === 'range' ? 'block' : 'none';
}

document.addEventListener('DOMContentLoaded', function() {
    // 初始化显示状态
    toggleSourceTypeFields();
    
    // 监听数据源变化
    document.getElementById('{{ form.data_source.id_for_label }}').addEventListener('change', toggleSourceTypeFields);
    
    // 监听报警条件变化
    document.querySelectorAll('.condition').forEach(select => {
        select.addEventListener('change', function() {
            toggleThresholdFields(this);
        });
    });
});
</script>
{% endblock %}
{% endblock %} 